import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'appScaffold.dart';
import 'gqWebView.dart';

enum WebTitleColor { light, dark }

typedef _JavascriptCallback = void Function(Map<String, dynamic>);

class GQWebViewPage extends StatefulWidget {
  String? url;
  String? title;
  String? userAgent;
  bool showTitleBar;
  bool showStatusBar;
  bool showHomeIndicator;
  Color titleBarColor;
  WebTitleColor titleColor;

  GQWebViewPage({
    ///url
    this.url,

    ///网页标题
    this.title,
    this.userAgent,

    ///是否显示标题栏
    this.showTitleBar = true,

    ///是否隐藏状态栏
    this.showStatusBar = true,

    ///是否显示/隐藏指示器
    this.showHomeIndicator = true,

    ///标题栏颜色
    this.titleBarColor = Colors.white,

    ///网页标题颜色
    this.titleColor = WebTitleColor.dark,
  }) {
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark);
  }

  @override
  GQWebViewPageState createState() => GQWebViewPageState();
}

class GQWebViewPageState extends State<GQWebViewPage> with WidgetsBindingObserver {
  GlobalKey<GQWebViewState> webViewKey = GlobalKey<GQWebViewState>();

  bool _showTitleBarForced = false;
  bool isBackNative = false;
  String netWorkStatus = "wifi";
  _JavascriptCallback? callBack;
  _JavascriptCallback? keyboardHeightCallBack;

  @override
  void initState() {
    super.initState();
    //2.页面初始化的时候，添加一个状态的监听者
    WidgetsBinding.instance?.addObserver(this);

    //初始化默认值
    widget.showTitleBar = true;
    widget.showStatusBar = true;
    widget.showHomeIndicator = true;
    widget.titleBarColor = Colors.white;
    widget.titleColor = WebTitleColor.dark;

  }

  @override
  void didChangeMetrics() {
    super.didChangeMetrics();
    if (keyboardHeightCallBack != null) {
      WidgetsBinding.instance?.addPostFrameCallback((_) {
        if (MediaQuery.of(context).viewInsets.bottom != 0) {
          keyboardHeightCallBack?.call({"height": MediaQuery.of(context).viewInsets.bottom});
          print("键盘高度" + MediaQuery.of(context).viewInsets.bottom.toString());
        }
      });
    }
  }

  @override
  void dispose() {
    //3. 页面销毁时，移出监听者
    WidgetsBinding.instance?.removeObserver(this);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    //mainWebView = GQWebView(url: "http://172.17.15.19/test.html");

    var args = ModalRoute.of(context)?.settings.arguments;
    if (args is Map<String, dynamic>) {
      if (args["url"] != null) {
        widget.url = args["url"];
      }

      if (args["__title"] != null) {
        widget.title = args["__title"];
      } else if (args["title"] != null) {
        widget.title = args["title"];
      }

      if (args["userAgent"] != null) {
        widget.userAgent = args["userAgent"];
      }

      if (args["__showTitleBar"] != null) {
        bool __showTitleBar = "false" != args["__showTitleBar"];
        widget.showTitleBar = __showTitleBar;
      }
      if (args["__titleBarColor"] != null) {
        var titleBarColorString = args["__titleBarColor"];
        if (titleBarColorString != null) {
          widget.titleBarColor = Color(int.tryParse(titleBarColorString) ?? 0xFFFFFFFF);
        }
      }

      if (args["__titleColor"] != null) {
        WebTitleColor __titleColor =
            "light" == args["__titleColor"] ? WebTitleColor.light : WebTitleColor.dark;
        widget.titleColor = __titleColor;
      }
      if (args["__showStatusBar"] != null) {
        bool __showStatusBar = "false" != args["__showStatusBar"];
        widget.showStatusBar = __showStatusBar;
      }
      if (args["__showHomeIndicator"] != null) {
        bool __showHomeIndicator = "false" != args["__showHomeIndicator"];
        widget.showHomeIndicator = __showHomeIndicator;
      }
    }

    return WillPopScope(
      child:  Scaffold(
         body: Container(
          color: widget.titleBarColor,
          child: SafeArea(
            top: true,
            bottom: widget.showHomeIndicator,
            child: Container(
              color: widget.titleBarColor,
              child: Column(
                mainAxisSize: MainAxisSize.max,
                children: [
                  Expanded(
                    child: Container(
                        child: GQWebView(
                          key: webViewKey,
                          url: widget.url,
                          title: widget.title,
                          userAgent: widget.userAgent,
                        )),
                  )
                ],
              ),
            ),
          ),
        ),
      ),
      onWillPop: () async {
        var isback = await webViewKey.currentState?.goBack();
        if (isback == true) return false;
        if ((widget.url ?? "").contains("willPop=false")) return false;
        return true;
      },
    );
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    switch (state) {
      //进入应用时候不会触发该状态 应用程序处于可见状态，并且可以响应用户的输入事件。它相当于 Android 中Activity的onResume
      case AppLifecycleState.resumed:
        print("应用进入前台======");
        // _webViewController?.evaluateJavascript("appLifecycleState_resumed()");
        if (callBack != null) {
          callBack?.call({"state": "1"});
          callBack = null;
        }
        break;
      //应用状态处于闲置状态，并且没有用户的输入事件，
      // 注意：这个状态切换到 前后台 会触发，所以流程应该是先冻结窗口，然后停止UI
      case AppLifecycleState.inactive:
        print("应用处于闲置状态，这种状态的应用应该假设他们可能在任何时候暂停 切换到后台会触发======");
        break;
      //当前页面即将退出
      case AppLifecycleState.detached:
        print("当前页面即将退出======");
        break;
      // 应用程序处于不可见状态
      case AppLifecycleState.paused:
        callBack?.call({"state": "2"});
        print("应用处于不可见状态 后台======");
        break;
      case AppLifecycleState.hidden:
        // TODO: Handle this case.
    }
  }

  void _backButtonClick() async {
    print("不知道为什么加上print才能生效"); //不知道为什么加上print才能生效
    if (isBackNative == true) {
      Navigator.of(context).pop();
    } else {
      var isback = await webViewKey.currentState?.goBack();
      if (isback == false) {
        Navigator.of(context).pop();
      }
    }
  }

  ///隐藏导航栏
  void hideTitleBar() {
    setState(() {
      widget.showTitleBar = false;
    });
  }

  ///显示导航栏
  void showTitleBar() {
    setState(() {
      widget.showTitleBar = true;
    });
  }

  void showTitleBarInError(bool isShow) {
    setState(() {
      _showTitleBarForced = isShow;
    });
  }

  void close() {
    Navigator.of(context).pop();
  }

}
